#include "clientHead/epoll.h"
#include "clientHead/order_analyse.h"

int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 3);
    char command[] = "请输入您需要的功能>>";
    order_train_t* orderTrain = (order_train_t*)calloc(1, sizeof(order_train_t));
    order_train_t* retTrain = (order_train_t*)calloc(1, sizeof(order_train_t));
    while(1){
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        struct sockaddr_in servaddr;
        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(atoi(argv[2]));
        servaddr.sin_addr.s_addr = inet_addr(argv[1]);
        
        int epfd = epoll_create(1);
        epollAdd(epfd, STDIN_FILENO);
        struct epoll_event readySet[5];
        write(STDOUT_FILENO, command, strlen(command));
        while(1){
            int recvFlag = 0;
            int readyNum = epoll_wait(epfd, readySet, 5, -1);
            for(int i = 0; i < readyNum; ++i){
                if(readySet[i].data.fd == STDIN_FILENO){
                    bzero(orderTrain, sizeof(order_train_t));
                    ssize_t sret = read(STDIN_FILENO, orderTrain->train_data, sizeof(orderTrain->train_data));                    
                    int ret = order_judg(orderTrain->train_data, orderTrain);
                    if(ret == -1){
                        write(STDOUT_FILENO, command, strlen(command));
                        break;
                    }
                    // 先读取，后连接
                    connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
                    // 将成功连接的socket加入监听集合
                    epollAdd(epfd, sockfd);
                    sendTrain(sockfd, orderTrain);
                }
                if(readySet[i].data.fd == sockfd){
                    // 接收到消息恢复，删除监听，断开连接
                    printf("\n");
                    bzero(retTrain, sizeof(order_train_t));
                    epollDel(epfd, sockfd);
                    recvTrain(sockfd, retTrain);
                    close(sockfd);
                    recvFlag = 1;
                    printf("\n");
                }
            }
            // 成功接收到回复，重置socket
            if(recvFlag){
                break;
            }
        }
    }
    return 0;
}


